<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\model\ChainDailyStatistics;
use app\common\model\EthAccount;
use app\common\model\EthAccountLog;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserBlackRecord;
use app\common\model\UserKingInvestment;
use app\common\model\Wallet;
use think\Db;

/**
 * 会员逻辑
 */
class Member extends AdminBase
{

    /**
     * 获取会员信息
     */
    public function getMemberInfo($where = [], $field = true)
    {

        $info = $this->modelMember->getInfo($where, $field);

        $info['leader_nickname'] = $this->modelMember->getValue(['id' => $info['leader_id']], 'nickname');
        return $info;
    }

    /**
     * 获取会员列表
     */
    public function getMemberList($data = [], $field = 'a.*,b.username as leader_nickname', $order = '', $paginate = DB_LIST_ROWS)
    {
        $where = $where1 = [];
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }
        if (!empty($data['uid'])) {
            $where['a.id'] = $data['uid'];
        }

        if (!empty($data['username'])) {
            $where['a.username|a.mobile'] =  $data['username'];
        }
        if (!empty($data['level_id'])) {
            $where['a.level_id'] =  $data['level_id'];
        }
        if (!empty($data['is_black'])) {
            $where['a.is_black'] =  $data['is_black']-1;
        }
        if (!empty($data['is_king'])) {
            $where['a.is_king'] =  $data['is_king']-1;
        }
        if (!empty($data['level_id'])) {
            $where['a.level_id'] =  $data['level_id'];
        }
        if (!empty($data['reg_ip'])) {
            $where['a.reg_ip'] =  $data['reg_ip'];
        }
        if (!empty($data['uuid'])) {
            $where['a.uuid'] =  $data['uuid'];
        }
        if (!empty($data['mobile'])) {
            $where['a.mobile'] = $data['mobile'];
        }
        if (!empty($data['is_lose'])) {
            $where['a.loss_bet'] =['gt',0];
        }
        if (!empty($data['leader_id'])  ) {
         
          $where['b.username|b.mobile'] = $data['leader_id'];
          
        }

        $where['a.status'] = 1;
        $where['a.is_inside'] = 0;
        if(isset($data['type']) && $data['type']==2){
            $list =  \app\common\model\Member::alias('a')->field($field)->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->order($order)->paginate(10, false, ['query' => $data]);
            $count = \app\common\model\Member::alias('a')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->count();
            $ids =  \app\common\model\Member::alias('a')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->column('a.id');
            //总包
            $arr['account1']=$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>1])->sum('balance')+$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>1])->sum('freeze_balance')+0;
            //理财包
            $arr['account2']=$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>3])->sum('balance')+$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>3])->sum('freeze_balance')+0;
            //eth
            $arr['account3']=$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>6])->sum('balance')+$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>6])->sum('freeze_balance')+$this->modelEthAccount->where(['user_id' => ['in', $ids]])->sum('eth_do')+$this->modelEthAccount->where(['user_id' => ['in', $ids]])->sum('eth_lock')+0;
            //btc
            $arr['account4']=$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>7])->sum('balance')+$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>7])->sum('freeze_balance')+$this->modelEthAccount->where(['user_id' => ['in', $ids]])->sum('btc_do')+$this->modelEthAccount->where(['user_id' => ['in', $ids]])->sum('btc_lock')+0;
            //usdt
            $arr['account5']=$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>8])->sum('balance')+$this->modelUserAccount->where(['user_id' => ['in', $ids],'wallet_id'=>8])->sum('freeze_balance')+$this->modelEthAccount->where(['user_id' => ['in', $ids]])->sum('usdt_do')+$this->modelEthAccount->where(['user_id' => ['in', $ids]])->sum('usdt_lock')+
            //店铺余额
            $arr['account6']=$this->modelOtcShop->where(['user_id' => ['in', $ids],'status'=>1,'state'=>2])->sum('number_do')+0;
            //撤回冻结
            $arr['account7']=$this->modelOtcShop->where(['user_id' => ['in', $ids],'status'=>1,'state'=>2])->sum('cancel_number')+0;
            //排队中
            $arr['account8']=$this->modelOtcShop->where(['user_id' => ['in', $ids],'status'=>1,'state'=>2])->sum('number_lock')+0;
            //赌王余额
            $arr['account9']=$this->modelGamblerKing->where(['user_id' => ['in', $ids],'status'=>1,'state'=>2])->sum('balance')+0;
            return ['count' => $count, 'list' => $list,'arr'=>$arr];
        }else{
            $list =  \app\common\model\Member::alias('a')->field($field)->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->order($order)->paginate(10, false, ['query' => $data]);
            $count = \app\common\model\Member::alias('a')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->count();
            $ids =  \app\common\model\Member::alias('a')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->column('a.id');
            $ke = $this->modelUserAccount->where(['user_id' => ['in', $ids], 'wallet_id' => 1])->sum('balance');
            $shan = $this->modelUserAccount->where(['user_id' => ['in', $ids], 'wallet_id' => 2])->sum('balance');
            $gc = $this->modelUserAccount->where(['user_id' => ['in', $ids], 'wallet_id' => 3])->sum('balance');
            $ke = $ke ? $ke : 0;
            $gc = $gc ? $gc : 0;
            $shan = $shan ? $shan : 0;
            return ['count' => $count, 'list' => $list, 'ke' => $ke, 'shan' => $shan, 'gc' => $gc];
        }





    }

    /**
     * 获取会员反馈列表
     */
    public function member_feedback($data = [], $field = 'm.*,b.nickname as leader_nickname', $order = '', $paginate = DB_LIST_ROWS)
    {
        $where = $where1 = [];
        if (!empty($data['uid'])) {
            $where['a.user_id'] = $data['uid'];
        }
        if (!empty($data['username'])) {
            $where['c.username'] =  $data['username'];
        }
        if (!empty($data['mobile'])) {
            $where['c.mobile'] = $data['mobile'];
        }


        $where['a.status'] = 1;


        $list = $this->modelUserFeedback->field($field)->alias('a')->join('__MEMBER__ c', 'a.user_id = c.id')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count = $this->modelUserFeedback->alias('a')->join('__MEMBER__ c', 'a.user_id = c.id')->where($where)->count();
        return ['list'=>$list,'count'=>$count];

    }
    /**
     * 获取会员登录记录列表
     */
    public function getloginlogList($data = [], $field = 'a.*,c.username,c.mobile', $order = '', $paginate = DB_LIST_ROWS)
    {
        $where =  [];
        if (!empty($data['username'])) {
            $where['a.user_id|c.username|c.mobile|a.ip'] =  $data['username'];
        }
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }


        $where['a.status'] = 1;


        $list = $this->modelLoginLog->field($field)->alias('a')->join('__MEMBER__ c', 'a.user_id = c.id')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count = $this->modelLoginLog->alias('a')->join('__MEMBER__ c', 'a.user_id = c.id')->where($where)->count();
        return ['list'=>$list,'count'=>$count];

    }


    /**
     * 获取会员亏损金额释放记录列表
     */
    public function lose_release_log($data = [], $field = 'a.*,c.username,c.mobile', $order = '', $paginate = DB_LIST_ROWS)
    {
        $where =  [];
        if (!empty($data['username'])) {
            $where['a.user_id|c.username|c.mobile|a.ip'] =  $data['username'];
        }
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }


        $where['a.status'] = 1;
        $where['a.type'] =1;

        $list = $this->modelAppAccountLog->field($field)->alias('a')->join('__MEMBER__ c', 'a.user_id = c.id')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count = $this->modelAppAccountLog->alias('a')->join('__MEMBER__ c', 'a.user_id = c.id')->where($where)->count();
        return ['list'=>$list,'count'=>$count];

    }
    /**
     * 导出会员列表
     */
    public function exportMemberList($data = [], $field = 'a.*', $order = 'id asc')
    {

        set_time_limit(0);
        $where = $where1 = [];
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }
        if (!empty($data['uid'])) {
            $where['a.id'] = $data['uid'];
        }
        if (!empty($data['username'])) {
            $where['a.username'] =  $data['username'];
        }
        if (!empty($data['mobile'])) {
            $where['a.mobile'] = $data['mobile'];
        }
      if (!empty($data['leader_id'])  ) {
         
          $where['b.username'] = $data['leader_id'];
          $where1['b.username'] = $data['leader_id'];
          
        }

        $where['a.status'] = 1;
        $where['a.is_inside'] = 0;
        if (!empty($where1)) {
            $list = $this->modelMember->alias('a')->field($field)->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->order($order)->select();
        } else {
            $list = $this->modelMember->alias('a')->field($field)->where($where)->order($order)->select();
        }


        foreach ($list as $k => $v) {
			$list[$k]['k'] = $k+1;
            $list[$k]['shop_text'] = $v->is_shop ? '是' : '否';
            $list[$k]['king_text'] = $v->is_king ? '是' : '否';
            $list[$k]['game_text'] = $v->game_return ? '是' : '否';
            $list[$k]['black_text'] = $v->is_black ? '是' : '否';
            $list[$k]['leader_nickname'] = $v->leader_nickname;
            $list[$k]['add_time'] = date('Y-m-d H:i:s', $v->create_time);
            $list[$k]['up_pwd_time1'] = $v->up_pwd_time?date('Y-m-d H:i:s', $v->up_pwd_time):'';
            $list[$k]['login_time'] =$v->last_login_time?date('Y-m-d H:i:s', $v->last_login_time):'';
            $list[$k]['ke'] = empty($v->wallet()[0]) ? 0 : $v->wallet()[0]['balance'];
            $list[$k]['shan'] = empty($v->wallet()[1]) ? 0 : $v->wallet()[1]['balance'];

        }

//        dd(json_decode(json_encode($list),true));
        $titles = "序号,UID,用户名,手机,分享账号,总包,理财包,注册时间,修改密码时间,最后登录时间,赌王,商家,游戏返点,封号";
        $keys = "k,id,username,mobile,leader_nickname,ke,shan,add_time,up_pwd_time1,login_time,king_text,shop_text,game_text,black_text";

        action_log('导出', '导出会员列表');

        export_excel($titles, $keys, $list, '会员列表');
    }

    /**
     * 获取会员列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where = [];

        !empty($data['search_data']) && $where['m.nickname|m.username|m.email|m.mobile'] =  $data['search_data'];

        if (!is_administrator()) {

            $member = session('member_info');

            if ($member['is_share_member']) {

                $ids = $this->getInheritMemberIds(MEMBER_ID);

                $ids[] = MEMBER_ID;

                $where['m.leader_id'] = ['in', $ids];

            } else {

                $where['m.leader_id'] = MEMBER_ID;
            }
        }

        return $where;
    }

    /**
     * 获取存在继承关系的会员ids
     */
    public function getInheritMemberIds($id = 0, $data = [])
    {

        $member_id = $this->modelMember->getValue(['id' => $id, 'is_share_member' => DATA_NORMAL], 'leader_id');

        if (empty($member_id)) {

            return $data;
        } else {

            $data[] = $member_id;

            return $this->getInheritMemberIds($member_id, $data);
        }
    }

    /**
     * 获取会员的所有下级会员
     */
    public function getSubMemberIds($id = 0, $data = [])
    {

        $member_list = $this->modelMember->getList(['leader_id' => $id], 'id', 'id asc', false);

        foreach ($member_list as $v) {

            if (!empty($v['id'])) {

                $data[] = $v['id'];

                $data = array_unique(array_merge($data, $this->getSubMemberIds($v['id'], $data)));
            }

            continue;
        }

        return $data;
    }

    /**
     * 会员添加到用户组
     */
    public function addToGroup($data = [])
    {

        $url = url('memberList');

        if (SYS_ADMINISTRATOR_ID == $data['id']) {

            return [RESULT_ERROR, '天神不能授权哦~', $url];
        }

        $where = ['member_id' => ['in', $data['id']]];

        $this->modelAuthGroupAccess->deleteInfo($where, true);

        if (empty($data['group_id'])) {

            return [RESULT_SUCCESS, '会员授权成功', $url];
        }

        $add_data = [];

        foreach ($data['group_id'] as $group_id) {

            $add_data[] = ['member_id' => $data['id'], 'group_id' => $group_id];
        }

        if ($this->modelAuthGroupAccess->setList($add_data)) {

            action_log('授权', '会员授权，id：' . $data['id']);

            $this->logicAuthGroup->updateSubAuthByMember($data['id']);

            return [RESULT_SUCCESS, '会员授权成功', $url];
        } else {

            return [RESULT_ERROR, $this->modelAuthGroupAccess->getError()];
        }
    }

    /**
     * 会员添加
     */
    public function memberAdd($data = [])
    {

        $validate_result = $this->validateMember->scene('add')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }

        $url = url('memberList');

        $data['nickname'] = $data['username'];
        if (!$referee_bean = $this->modelMember->getInfo(['username' => $data['leader']])) {
            return [RESULT_ERROR, '推荐人不存在'];
        }
        $data['pin_password'] = md5($data['pin_password'] . 'pin');
        $data['leader_id'] = $referee_bean['id'];
        $data['is_inside'] = DATA_DISABLE;
        Db::startTrans();
        try {
            $result = $this->modelMember->setInfo($data);
            UserAccount::addWallet($result);
            $member=$this->modelMember->getInfo(['id'=>$result]);


            //写入邀请人层级
            if($referee_bean['ceng_member']){
                $referee_bean->ceng_member=$result.','.$referee_bean['ceng_member'];

            }else{
                $referee_bean->ceng_member=$result;
            }
            $member->path=$result.','. $referee_bean->path;
            $member->dai_level=$referee_bean->dai_level+1;
            $member->dai_level=$referee_bean->dai_level+1;
            $member->team_id=$referee_bean['team_id'];
            $member->team_number=$referee_bean['team_number'];

            $member->save();
            $referee_bean->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }

        $result && action_log('新增', '新增会员，username：' . $data['username']);

        return $result ? [RESULT_SUCCESS, '会员添加成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
    }

    /**
     * 会员编辑
     */
    public function memberEdit($data = [])
    {

        $validate_result = $this->validateMember->scene('edit')->check($data);

//        if (!$validate_result) {
//
//            return [RESULT_ERROR, $this->validateMember->getError()];
//        }
        $mem = \app\common\model\Member::get($data['id']);
//        if ($mem['leader_id']) {
//            return [RESULT_ERROR, '用户已存在推荐人'];
//        }
        Db::startTrans();
        try {

//            if (!$data['password']) {
//                unset($data['password']);
//            }
            if(!isset($data['is_enable'])){
                $data['is_enable']=0;
            }
            if ($data['pin_password']) {

                $data['pin_password']=md5($data['pin_password'].'pin');
            }else{
                unset($data['pin_password']);
            }
            if($data['password']){
//                $data['password']=data_md5_key($data['password']);
            }else{
                unset($data['password']);
            }
            if(!isset($data['is_plan'])){
                $data['is_plan']=0;
            }
            if(!isset($data['is_banker'])){
                $data['is_banker']=0;
            }
            if(!isset($data['just_switch'])){
                $data['just_switch']=0;
            }
//                dd($data);
            $url = url('memberList');

            $result = $this->modelMember->setInfo($data);

            $result && action_log('编辑', '编辑会员，id：' . $data['id']);
            Db::commit();
            return $result ? [RESULT_SUCCESS, '会员编辑成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
        } catch (\Exception $e) {
            return [RESULT_ERROR, $e->getMessage()];
        }

    }

    /**
     * 修改密码
     */
    public function editPassword($data = [])
    {

        $validate_result = $this->validateMember->scene('password')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }

        $member = $this->getMemberInfo(['id' => $data['id']]);

        if (data_md5_key($data['old_password']) != $member['password']) {

            return [RESULT_ERROR, '旧密码输入不正确'];
        }

        $data['id'] = MEMBER_ID;

        $url = url('index/index');

        $result = $this->modelMember->setInfo($data);

        $result && action_log('编辑', '会员密码修改，id：' . $data['id']);

        return $result ? [RESULT_SUCCESS, '密码修改成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
    }

    /**
     * 设置会员信息
     */
    public function setMemberValue($where = [], $field = '', $value = '')
    {

        return $this->modelMember->setFieldValue($where, $field, $value);
    }

    /**
     * 会员删除
     */
    public function memberDel($where = [])
    {

        $url = url('memberList');

        if (SYS_ADMINISTRATOR_ID == $where['id'] || MEMBER_ID == $where['id']) {

            return [RESULT_ERROR, '天神和自己不能删除哦~', $url];
        }

        $result = $this->modelMember->deleteInfo($where);

        $result && action_log('删除', '删除会员，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '会员删除成功', $url] : [RESULT_ERROR, $this->modelMember->getError(), $url];
    }


    /**
     * 充值钱包
     */
    public function recharge($data)
    {
        $url = url('recharge/admin_recharge_log');
        Db::startTrans();
        if (empty($data['remark'])) {
            return [RESULT_ERROR, '充值备注不能为空'];
        }
        if (!$member = $this->modelMember->where(['username' => $data['username']])->order('id desc')->find()) {
            return [RESULT_ERROR, '用户不存在'];
        }
        if($data['type']==6){
            if (!$shop = $this->modelOtcShop->where(['user_name' => $data['username']])->order('id desc')->find()) {
                return [RESULT_ERROR, '商铺不存在'];
            }
        }
        $data['admin_name'] = session('member_info.username');
        $data['user_id'] =$member['id'];
        if ($data['balance'] != 0) {
            try {

                if($data['type']<4){
                    $data['form_wallet_id']=$data['type'];
                }
                if($data['type']==6){
                    $data['form_wallet_id']=33;
                }
                $arr = [
                    'type' => 12,
                    'form_wallet_id' => $data['form_wallet_id'],
                    'number' => $data['balance'],
                    'state' => 1,
                    'user_id' => $member['id'],
                    'remark'=>$data['remark'],
                    'admin_name'=>$data['admin_name'],

                ];
                if($data['type']==5){
                    $arr['is_legal_currency']=1;
                }
                
                    Transfer::create($arr);
                
                
                //充值记录
                if($data['type']<5){
                    $account = UserAccount::where(['user_id' => $data['user_id'], 'wallet_id' => $data['form_wallet_id']])->lock(true)->find();
                    $account->balance += $data['balance'];
                    if($account->balance<0 ){
                        return [RESULT_ERROR, '余额不足'];
                    }

                    $account->save();
                    $arr = [
                        'user_id' => $data['user_id'],
                        'number' => $data['balance'],
                        'wallet_id' => $data['form_wallet_id'],
                        'before_blance' => $account->balance - $data['balance'],
                        'after_blance' => $account->balance,
                        'type' => 1,
                        'remark'=>$data['remark'],
                    ];
                    if ($data['balance'] < 0) {
                        $arr['is_add'] = 2;
                    }
                    UserAccountLog::create($arr);
                }else if($data['type']<6){
                    //法币账户充值
                    $wallet=Wallet::get( $data['form_wallet_id']);
                    $do=$wallet['symbol'].'_do';
                    $account=EthAccount::where(['user_id'=>$member['id']])->lock(true)->find();
                    $account->$do+= $data['balance'];
                    if($account->$do<0 ){
                        return [RESULT_ERROR, '余额不足'];
                    }
                    $account->save();
                    $arr = [
                        'user_id' => $data['user_id'],
                        'number' => $data['balance'],
                        'wallet_id' => $data['form_wallet_id'],
                        'before_blance' => $account->$do - $data['balance'],
                        'after_blance' => $account->$do,
                        'type' => 9,
                        'remark'=>$data['remark'],
                    ];
                    if ($data['balance'] < 0) {
                        $arr['is_add'] = 2;
                    }
                    EthAccountLog::create($arr);

                }else{
                    $usdt_price = Db::name("wallet_price")->where(['symbol'=>'usdt'])->order("id desc")->find()['price'];

                    $shop->number_do+=$data['balance']/$usdt_price;
                    if($shop->number_do<0 ){
                        return [RESULT_ERROR, '余额不足'];
                    }
                    $shop->save();
                }


                Db::commit();

            } catch (\Exception $e) {

                Db::rollback();
                return [RESULT_ERROR, $e->getMessage()];
            }
        }

        return [RESULT_SUCCESS, '充值成功', $url];
    }


    /**
     * 锁定
     */
    public function update_info($where = [])
    {

        if(!empty($where['ids'])){

            \app\common\model\Member::where(['id'=>['in',$where['ids']]])->update(['is_company'=>$where['is_company']]);
            return  [RESULT_SUCCESS, '操作成功'];

        }else{
            if(isset($where['is_black']) ){
                if($where['is_black']=='0'){
                    $type=2;
                }else{
                    $type=1;
                }
                $content='后台操作';
                UserBlackRecord::create([
                    'type'=>$type,
                    'admin_name'=>session('member_info.username'),
                    'remark'=>$content,
                    'user_id'=>$where['id']
                ]);

            }

            if(isset($where['is_login']) ){
                $member=$this->modelMember->getInfo(['id'=>$where['id']]);
                if($where['is_login']==0){
                    $where['no_login_time']=time()+86400;
                }
                cache($member['username'].$member['id'],null);
                cache($member['username'].$member['id'].'pinpassword',null);
            }
            if(isset($where['is_otc']) ){
                if($where['is_otc']==0){
                    $where['penalty_time']=time()+86400;
                }

            }
            if(isset($where['login_token']) ){
                $where['login_token']='';
            }
            $result = $this->modelMember->setInfo($where);
            return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];


        }


    }

    /**
     * 设置会员信息
     */
    public function member_level($data)
    {
        $member = new \app\common\model\Member();

            if(empty($data['id'])){
                    $data['id']=2;
            }else{
                $data['id']=$member->where(['username|id|mobile'=>$data['id']])->value('id');
            }

        echo json_encode($member->member_tree($data['id']), JSON_UNESCAPED_UNICODE);
        die;
    }


    /**
     * 获取不良记录列表
     */
    public function bad_record($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['username'])) {
            $where['c.username|a.user_id'] =$data['username'] ;
        }

        if(!empty($data['mobile'])){
            $where['a.mobile']=$data['mobile'];
        }


        if(!empty($data['type'])){
            $where['a.type']=  $data['type'];
        }
        $where['a.status'] = 1;


        $list = $this->modelUserBadRecord->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->field($field)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count=$this->modelUserBadRecord->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->count();


        return ['count'=>$count,'list'=>$list];






    }

    /**
     * ip检测
     */

    public function getIpMemberList($name,$paginate=DB_LIST_ROWS){
        $list=$this->modelMember->where([$name=>['neq','']])->group($name)->paginate($paginate);
        $count=$this->modelMember->where([$name=>['neq','']])->group($name)->count();
        return ['count'=>$count,'list'=>$list];
    }

    /**
     * 在线会员
     */

    public function getSameMemberList($data,$paginate=DB_LIST_ROWS){
        $where=['a.login_token'=>['neq','']];
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }
        if (!empty($data['ip'])) {
            $where['a.reg_ip|a.last_login_ip'] = $data['ip'];
        }
        if (!empty($data['leader_name'])) {
            $where['b.username|b.mobile'] = $data['leader_name'];
        }
        if (!empty($data['username'])) {
            $where['a.username|a.mobile'] = $data['username'];
        }
        if (!empty($data['uuid'])) {
            $where['a.uuid'] = $data['uuid'];
        }
        if (!empty($data['area'])) {
            $where['a.last_login_area'] = $data['area'];
        }
        if (!empty($data['is_bet_frequently'])) {
            $where['a.is_bet_frequently'] = 1;
        }
        if(!empty($data['same_ip'])){
            $where=['a.last_login_ip'=>['neq','']];
            $list=$this->modelMember->alias('a')->field('a.*,b.username as leader_name')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->group('a.last_login_ip')->paginate($paginate);
            $count=$this->modelMember->alias('a')->field('a.*,b.username as leader_name')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->group('a.last_login_ip')->count();
        }else{
            $list=$this->modelMember->alias('a')->field('a.*,b.username as leader_name')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->paginate($paginate);
            $count=$this->modelMember->alias('a')->field('a.*,b.username as leader_name')->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->count();
        }

        return ['count'=>$count,'list'=>$list];
    }



    /**
     * 会员链上记账更多明细
     */
    public function getGameLogList($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }


        if(!empty($data['mobile'])){
            $where['a.mobile']=$data['mobile'];
        }

        if(!empty($data['user_id'])){

            $where['user_id']=$data['user_id'];
            $where['entrust_count']=0;
        }
        $where['a.status'] = 1;
        $where['a.type'] = 4;


        $list = $this->modelGamesLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->field($field)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count=$this->modelGamesLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->count();


        return ['count'=>$count,'list'=>$list];






    }


    /**
     * 会员链上记账更多明细
     */
    public function getChainLogList($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }





        $where['a.status'] = 1;



        $list = $this->modelChainDailyStatistics->alias('a')->field($field)->where($where)->field($field)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count=$this->modelChainDailyStatistics->alias('a')->where($where)->count();


        return ['count'=>$count,'list'=>$list];






    }



    /**
     * 链上记账明细添加
     */
    public function chain_statistics_add($data = [])
    {



        $url = url('chain_statistics');

        $datas=[];


        $total_address_count = 0;
        foreach ($data['address_count'] as $key=>$value){
            $total_address_count += $value;
        }
        $add_count=Db::name("coin_address")->where(["mid"=>6,'status'=>0,'type'=>1,'create_time'=>['between',[strtotime($data['date2'].' 00:00:00'),strtotime($data['date3'].' 23:59:59')]]])->count();
        if($add_count<$total_address_count){
            return [RESULT_ERROR, '地址数量不足,还需要创建'.$total_address_count-$add_count.'个地址'];
        }

        $total_address = Db::name("coin_address")->field('address')->where(["mid"=>6,'status'=>0,'type'=>1,'create_time'=>['between',[strtotime($data['date2'].' 00:00:00'),strtotime($data['date3'].' 23:59:59')]]])->limit($total_address_count)->select();
        $count =$winner_money=$lose_money= 0;
        foreach ($data['address_count'] as $k=>$v){

            for($i=$v;$i>0;$i--){
                $arr=[
                    'address'=>$total_address[$count]['address'],
                    'state'=>1,
                    'number'=>$data['amount'][$k],
                    'investment_lose_number'=>0,
                    'create_time' => strtotime($data['date1'].' 00:00:01'),
                    'update_time'=>time(),
                    'type'=>$data['flag'][$k],
                ];
                $arrs[]=$arr;
                $count++;
                if($data['flag'][$k]==1){
                    $lose_money+=$data['amount'][$k];
                }else{
                    $winner_money+=$data['amount'][$k];
                }

            }

        }

        $this->modelGamesDailyLog->insertAll($arrs);

        $info=ChainDailyStatistics::where(['create_time'=>['between',[strtotime($data['date1'].' 00:00:00'),strtotime($data['date1'].' 23:59:59')]]])->find();
        if($info){
            $info->winner_money+=$winner_money;
            $info->lose_money+=$lose_money;
            $info->transfer_count+=$count;
            $info->save();

        }else{
            ChainDailyStatistics::create([
                'winner_money'=>$winner_money,
                'lose_money'=>$lose_money,
                'transfer_count'=>$count,
                'create_time'=>strtotime($data['date1'].' 00:05:00')
            ]);
        }







        return [RESULT_SUCCESS, '操作成功', $url];
    }



}
